var UUID = require("uuid");
var fs = require("fs");
var path = require("path");
const ossTool = require("../service/ossTool");
const funTool = require("../../tool/funTool");

module.exports = {
    "POST /file/upload_Img": async(ctx, next) => {
        const files = ctx.request.files; // 获取上传文件
        let fileArray = [];
        let rootPath = path.join(__dirname, "../../upload/imgs");
        for (var key in files) {
            fileArray.push(files[key]);
        }

        //创建文件夹
        await funTool.mkdirsSync(rootPath);

        let resArray = [];
        fileArray.forEach((file) => {
            // 创建可读流
            const reader = fs.createReadStream(file.path);

            let filePath = `/${UUID.v1() + "_" + file.name}`;
            // 创建可写流
            const upStream = fs.createWriteStream(path.join(rootPath, filePath));
            // 可读流通过管道写入可写流

            reader.pipe(upStream);

            resArray.push({ name: file.name, path: path.join("/imgs", filePath) });
        });

        ctx.success(resArray);
    },
    "POST /file/upload_oos_img": async(ctx, next) => {
        let fileArray = [];
        const files = ctx.request.files; // 获取上传文件
        for (var key in files) {
            fileArray.push(files[key]);
        }
        let data = await ossTool.putImg(fileArray[0]);
        if (data.path) {
            return ctx.success(data);
        } else {
            return ctx.fail();
        }
    },
};